/**
  **************************************************************************
  * @file     main.c
  * @version  v2.0.0
  * @date     2020-11-02
  * @brief    main program
  **************************************************************************
  *                       Copyright notice & Disclaimer
  *
  * The software Board Support Package (BSP) that is made available to
  * download from Artery official website is the copyrighted work of Artery.
  * Artery authorizes customers to use, copy, and distribute the BSP
  * software and its related documentation for the purpose of design and
  * development in conjunction with Artery microcontrollers. Use of the
  * software is governed by this copyright notice and the following disclaimer.
  *
  * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES,
  * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS,
  * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR
  * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS,
  * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
  *
  **************************************************************************
  */

#include "at32f403a_407_board.h"
#include "at32f403a_407_clock.h"
#include "i2c_application.h"
#include "mg90s.h"
#include "at32f403a_407_wk_config.h"
#include <stdio.h>
#include "motor_control.h"
#include"i2c_management.h"
#include <bright_regim.h>
//#include <stdbool.h>





/** @addtogroup AT32F403A_periph_examples
  * @{
  */

/** @addtogroup 403A_I2C_communication_int I2C_communication_int
  * @{
  */



#define I2C_TIMEOUT                      0xffffffFF

#define I2Cx_SPEED                       100000
#define I2Cx_ADDRESS                     0x15<<1

#define I2Cx_PORT                        I2C2
#define I2Cx_CLK                         CRM_I2C2_PERIPH_CLOCK

#define I2Cx_SCL_PIN                     GPIO_PINS_9
#define I2Cx_SCL_GPIO_PORT               GPIOB
#define I2Cx_SCL_GPIO_CLK                CRM_GPIOB_PERIPH_CLOCK

#define I2Cx_SDA_PIN                     GPIO_PINS_11
#define I2Cx_SDA_GPIO_PORT               GPIOB
#define I2Cx_SDA_GPIO_CLK                CRM_GPIOB_PERIPH_CLOCK

#define I2Cx_EVT_IRQn                    I2C2_EVT_IRQn
#define I2Cx_ERR_IRQn                    I2C2_ERR_IRQn

#define BUF_SIZE                         7

#define TMRx_PR 100


#define CW  0 // clockwise         по часовой
#define CCW 1 // counterclock-wise против часовой

WorkParams workParams;

MotorData motorA;
MotorData motorB;

uint8_t tx_buf[BUF_SIZE] = {0x01, 0x02};//, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
uint8_t rx_buf[BUF_SIZE] = {};

void* motorA_ptr = &motorA;
void* motorB_ptr = &motorB;
void* work_param_ptr = &workParams;


uint16_t usart2_tx_buffer = 1;
uint8_t usart2_rx_buffer;
uint8_t usart2_tx_buffer_size = 1;
int32_t odometr_div18 = 0;
int32_t odometr_bef = 0;
int32_t odometr_next = 0;
int16_t speed_hall = 0;
uint16_t direction = CW;
uint16_t timer_period = 0;
uint16_t channel1_pulse = 0, channel2_pulse = 0, channel3_pulse = 0,
		channel4_pulse = 0;

uint16_t timer_period_3 = 0;
uint16_t  channel3_pulse_3 = 0, channel4_pulse_3 = 0;

uint16_t timer_period_5 = 0;
uint16_t  channel3_pulse_5 = 0, channel4_pulse_5 = 0;


enum motor_mode mtr_mode;

//bool flag_timeout = false;

uint16_t PWM_DataLength = 0;
uint16_t src_buffer[360] = { };

void usart_configuration(void);
void usart2_tx_rx_handler(void);
void crm_configuration(void);
void gpio_configuration(void);
void tmr_configuration(void);
void dma_configuration(void);
void TMR4_DMA_Duty_Cycle(void);
void tmr5_handler();

i2c_handle_type hi2cx;


void i2c_lowlevel_init(i2c_handle_type* hi2c);

gpio_init_type gpio_init_struct = { 0 };
tmr_output_config_type tmr_output_struct;
crm_clocks_freq_type crm_clocks_freq_struct = { 0 };


tmr_output_config_type tmr_output_struct, tmr4_output_struct;


/**
  * @brief  error handler program
  * @param  i2c_status
  * @retval none
  */

void usart_configuration(void) {
	gpio_init_type gpio_init_struct;

	/* enable the usart2 and gpio clock */
	crm_periph_clock_enable(CRM_USART2_PERIPH_CLOCK, TRUE);
	crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);

	gpio_default_para_init(&gpio_init_struct);
	/* configure the usart2 tx pin */
	gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
	gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
	gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
	gpio_init_struct.gpio_pins = GPIO_PINS_2;
	gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
	gpio_init(GPIOA, &gpio_init_struct);

	/* config usart nvic interrupt */
	nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
	nvic_irq_enable(USART2_IRQn, 0, 0);

	/* configure usart2 param */
	usart_init(USART2, 115200, USART_DATA_8BITS, USART_STOP_1_BIT);
	usart_transmitter_enable(USART2, TRUE);
	usart_receiver_enable(USART2, TRUE);

	/* enable usart2 and usart3 interrupt */
	usart_enable(USART2, TRUE);
	usart_interrupt_enable(USART2, USART_TDBE_INT, TRUE);

}

//void delay_unblocked(uint32_t ms) {
//
//	float overflow_count = ms * 1.65f;
//
//  // Сбрасываем флаг тайм-аута
//  flag_timeout = false;
//
//  tmr_interrupt_enable(TMR5, TMR_OVF_INT, TRUE);
//  // Запускаем таймер (если он еще не запущен)
//  if (!tmr_flag_get(TMR5, TMR_OVF_INT)) {
//    tmr_counter_enable(TMR5, TRUE);
//  }
//
//  // Ожидаем нужное количество переполнений
//  while (overflow_count > 0) {
//    while (!flag_timeout); // Ждем переполнения
//    flag_timeout = false; // Сбрасываем флаг
//    overflow_count--;
//  }
//
//}
//
//void tmr5_handler(){
//	  if (tmr_flag_get(TMR5, TMR_OVF_FLAG) != RESET) {
//	    tmr_flag_clear(TMR5, TMR_OVF_FLAG);
//	    flag_timeout = true;
//	  }
//}


/*init ports */
void mn_gpio_init(void) {

	/* timer1 output pin Configuration */
	gpio_init_struct.gpio_pins = GPIO_PINS_3; //А3, четвёртый канал TMR5
	gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
	gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
	gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
	gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
	gpio_init(GPIOA, &gpio_init_struct);

	gpio_init_type gpio_init_struct;
	gpio_default_para_init(&gpio_init_struct);
	/* configure PB1 tmr3_ch4 as output*/
	gpio_init_struct.gpio_pins = GPIO_PINS_1;
	gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
	gpio_init(GPIOB, &gpio_init_struct);
}

void gpio_configuration(void) {
	gpio_init_type gpio_init_struct;

	gpio_default_para_init(&gpio_init_struct);

	/* configure PB7 tmr4_ch2 as output*/
	gpio_init_struct.gpio_pins = GPIO_PINS_7;
	gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
	gpio_init(GPIOB, &gpio_init_struct);
}

/**
 * @brief  configure the tmr parameters.
 * @param  none
 * @retval none
 */
void tmr_configuration(void) {
	/* Init TMR4 */
	tmr_base_init(TMR4, TMRx_PR - 1, 2);
	tmr_cnt_dir_set(TMR4, TMR_COUNT_UP);

	/* TMR configuration as output mode */
	tmr_output_default_para_init(&tmr_output_struct);
	tmr_output_struct.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A;
	tmr_output_struct.oc_output_state = TRUE;
	tmr_output_struct.oc_polarity = TMR_OUTPUT_ACTIVE_LOW;

	/* TMR4 channel 2 configuration */
	tmr_output_channel_config(TMR4, TMR_SELECT_CHANNEL_2, &tmr_output_struct);

	/* enable tmr output channel buffer */
	tmr_output_channel_buffer_enable(TMR4, TMR_SELECT_CHANNEL_2, TRUE);
}

/**
 * @brief  configure the dma parameters.
 * @param  none
 * @retval none
 */
void dma_configuration(void) {
	dma_init_type dma_init_struct = { 0 };
	uint16_t index = 0;

	while (index < PWM_DataLength) {
		src_buffer[index] = (uint16_t) (((uint32_t) (src_buffer[index])
				* (TMRx_PR)) / (100));
		index++;
	}

	/* dma1 channel7 configuration */
	dma_default_para_init(&dma_init_struct);

	dma_init_struct.buffer_size = PWM_DataLength;
	dma_init_struct.direction = DMA_DIR_MEMORY_TO_PERIPHERAL;
	dma_init_struct.memory_base_addr = (uint32_t) src_buffer;
	dma_init_struct.memory_data_width = DMA_MEMORY_DATA_WIDTH_HALFWORD;
	dma_init_struct.memory_inc_enable = TRUE;
	dma_init_struct.peripheral_base_addr = (uint32_t) &TMR4->c2dt;
	dma_init_struct.peripheral_data_width = DMA_PERIPHERAL_DATA_WIDTH_HALFWORD;
	dma_init_struct.peripheral_inc_enable = FALSE;
	dma_init_struct.priority = DMA_PRIORITY_HIGH;
	dma_init_struct.loop_mode_enable = FALSE;
	dma_init(DMA1_CHANNEL7, &dma_init_struct);
}


void TMR4_DMA_Duty_Cycle(void) {

	/* set tmr channel CC value */
	tmr_channel_value_set(TMR4, TMR_SELECT_CHANNEL_2, 0);

	/* config set the number of data to be transferred by dma */
	dma_channel_enable(DMA1_CHANNEL7, FALSE);
	dma_data_number_set(DMA1_CHANNEL7, PWM_DataLength);
	dma_channel_enable(DMA1_CHANNEL7, TRUE);

	/* TMR enable counter */
	tmr_counter_enable(TMR4, TRUE);

	/* wait for the end of dma transfer */
	while (!dma_flag_get(DMA1_FDT7_FLAG))
		;
	/* Clear dma flag */
	dma_flag_clear(DMA1_FDT7_FLAG);

	/* Clear TMR4 update Interrupt  pending bit */
	tmr_flag_clear(TMR4, TMR_OVF_FLAG);
	while (SET != tmr_flag_get(TMR4, TMR_OVF_FLAG))
		;
	/* Clear TMR4 update Interrupt  pending bit */
	tmr_flag_clear(TMR4, TMR_OVF_FLAG);
	while (SET != tmr_flag_get(TMR4, TMR_OVF_FLAG))
		;

	/* TMR disable counter */
	tmr_counter_enable(TMR4, FALSE);

}


void usart2_tx_rx_handler(void) {
	if (usart_flag_get(USART2, USART_TDBE_FLAG) != RESET) {
		/* write one byte to the transmit data register */
		// Передача старшего байта
		uint8_t high_byte = (uint8_t) (usart2_tx_buffer >> 8);
		usart_data_transmit(USART2, high_byte);

		// Передача младшего байта
		uint8_t low_byte = (uint8_t) usart2_tx_buffer;
		usart_data_transmit(USART2, low_byte);

		/* disable the usart2 transmit interrupt */
		usart_interrupt_enable(USART2, USART_TDBE_INT, FALSE);
	}
}

// переписать по нормальному !!!!!!!!!!!!!!!!!
void usart2_tx_without_int() {
	int64_t odo_path = motorA.currentParrot;  // Примерное значение переменной
	char buffer[20] = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
			'0', '0', '0', '0', '0', '0', '0', '0', '0' };
	// Увеличиваем размер буфера для безопасного хранения длинных строк

	int8_t ostatok = 0;
	int8_t iter = 0;
	int8_t sight = 0;

	if (motorA.direction) {
		sight = 0x4d;
	}

	if (odo_path < 0) {
		odo_path *= -1;
	}

	if (odo_path == 0) {
		buffer[iter++] = '0';
	} else {
		while (odo_path > 0) {
			ostatok = odo_path % 10;
			odo_path /= 10;
			buffer[iter++] = '0' + ostatok;  // Преобразование числа в символ
		}
	}

	if (sight) {
		buffer[iter] = '-';
		iter++;
	}

	buffer[iter++] = ' ';

	ostatok = 0;
	int8_t sight_2 = 0;

	int16_t odo_path_2 = 100 - (motorA.setParrot / 7.89);

	if (motorA.direction) {
		sight_2 = 0x4d;
	}

	if (odo_path_2 == 0) {
		buffer[iter++] = '0';
	} else {
		while (odo_path_2 > 0) {
			ostatok = odo_path_2 % 10;
			odo_path_2 /= 10;
			buffer[iter++] = '0' + ostatok;  // Преобразование числа в символ
		}
	}

	if (sight_2) {
		buffer[iter] = '-';
		iter++;
	}

	buffer[iter++] = ' ';
	buffer[iter++] = 'A';
	buffer[iter++] = ' ';
	buffer[iter++] = ' ';
	buffer[iter++] = ' ';

	odo_path = motorB.currentParrot;  // Примерное значение переменной
	// Увеличиваем размер буфера для безопасного хранения длинных строк

	ostatok = 0;
	sight = 0;

	if (!motorB.direction) {
		sight = 0x4d;
	}

	if (odo_path < 0) {
		odo_path *= -1;
	}

	if (odo_path == 0) {
		buffer[iter++] = '0';
	} else {
		while (odo_path > 0) {
			ostatok = odo_path % 10;
			odo_path /= 10;
			buffer[iter++] = '0' + ostatok;  // Преобразование числа в символ
		}
	}

	if (sight) {
		buffer[iter] = '-';
		iter++;
	}

	buffer[iter++] = ' ';

	ostatok = 0;
	sight_2 = 0;

	odo_path_2 = 100 - (motorA.setParrot / 7.89);

	if (motorB.direction) {
		sight_2 = 0x4d;
	}

	if (odo_path_2 == 0) {
		buffer[iter++] = '0';
	} else {
		while (odo_path_2 > 0) {
			ostatok = odo_path_2 % 10;
			odo_path_2 /= 10;
			buffer[iter++] = '0' + ostatok;  // Преобразование числа в символ
		}
	}

	if (sight_2) {
		buffer[iter] = '-';
		iter++;
	}

	buffer[iter++] = ' ';
	buffer[iter++] = 'B';


	buffer[iter] = '\r';
	buffer[++iter] = '\n';

	// Развернуть строку
	for (int i = 0; i < iter / 2; ++i) {
		char temp = buffer[i];
		buffer[i] = buffer[iter - i - 1];
		buffer[iter - i - 1] = temp;
	}
	//
	// Отправка строки через UART
	for (size_t i = 0; i <= iter; i++) {
		while (!USART2->sts_bit.tdbe)
			;
		usart_data_transmit(USART2, (int8_t) buffer[i]);
	}
}


/**
  * @brief  initializes peripherals used by the i2c.
  * @param  none
  * @retval none
  */
void i2c_lowlevel_init(i2c_handle_type* hi2c)
{
  gpio_init_type gpio_initstructure;

  if(hi2c->i2cx == I2Cx_PORT)
  {
    /* i2c periph clock enable */
    crm_periph_clock_enable(I2Cx_CLK, TRUE);
    crm_periph_clock_enable(I2Cx_SCL_GPIO_CLK, TRUE);
    crm_periph_clock_enable(I2Cx_SDA_GPIO_CLK, TRUE);

    /* gpio configuration */
    gpio_initstructure.gpio_out_type       = GPIO_OUTPUT_OPEN_DRAIN;
    gpio_initstructure.gpio_pull           = GPIO_PULL_UP;
    gpio_initstructure.gpio_mode           = GPIO_MODE_MUX;
    gpio_initstructure.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE;

    /* configure i2c pins: scl */
    gpio_initstructure.gpio_pins = I2Cx_SCL_PIN;
    gpio_init(I2Cx_SCL_GPIO_PORT, &gpio_initstructure);

    /* configure i2c pins: sda */
    gpio_initstructure.gpio_pins = I2Cx_SDA_PIN;
    gpio_init(I2Cx_SDA_GPIO_PORT, &gpio_initstructure);

    /* configure and enable i2c interrupt */
    nvic_irq_enable(I2Cx_EVT_IRQn, 0, 0);
    nvic_irq_enable(I2Cx_ERR_IRQn, 0, 0);

    i2c_init(hi2c->i2cx, I2C_FSMODE_DUTY_2_1, I2Cx_SPEED);

    i2c_own_address1_set(hi2c->i2cx, I2C_ADDRESS_MODE_7BIT, I2Cx_ADDRESS);


  }
}


void wk_tmr5_init(void) {
	/* tmr1 configuration generate 7 pwm signals with 4 different duty cycles:
	 prescaler = 0, tmr1 counter clock = system_core_clock

	 the objective is to generate 7 pwm signal at 17.57 khz:
	 - tim1_period = (system_core_clock / 17570) - 1
	 the channel 1 and channel 1n duty cycle is set to 50%
	 the channel 2 and channel 2n duty cycle is set to 37.5%
	 the channel 3 and channel 3n duty cycle is set to 25%
	 the channel 4 duty cycle is set to 12.5%
	 the timer pulse is calculated as follows:
	 - channelxpulse = duty_cycle * (tim1_period - 1) / 100 */

	/* compute the value to be set in arr regiter to generate signal frequency at 20khz */

	uint16_t timer_period_5 =  47535;
	//  /* compute ccr1 value to generate a duty cycle at 50% for channel 1 and 1n */
//	channel1_pulse = (uint16_t)(((uint32_t) 5 * (timer_period - 1)) / 10);

	/* compute ccr2 value to generate a duty cycle at 37.5%  for channel 2 and 2n */
//	channel2_pulse = (uint16_t) (((uint32_t) 375 * (timer_period - 1)) / 1000);

	/* compute ccr3 value to generate a duty cycle at 25%  for channel 3 and 3n */
	channel3_pulse_5 = (uint16_t) (((uint32_t) 2 * (timer_period_5 - 1)) / 1000);

	/* compute ccr4 value to generate a duty cycle at 12.5%  for channel 4 */
//	channel4_pulse_5 = (uint16_t)(((uint32_t) 2 * (timer_period- 1)) / 1000);
	channel4_pulse_5 = (uint16_t)(((uint32_t) 500 * (timer_period_5 - 1)) / 1000);
	tmr_base_init(TMR5, timer_period_5, 1);
	tmr_cnt_dir_set(TMR5, TMR_COUNT_UP);

	/* channel 1, 2, 3 and 4 configuration in output mode */
	tmr_output_default_para_init(&tmr_output_struct);
	tmr_output_struct.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_B;
	tmr_output_struct.oc_output_state = TRUE;
	tmr_output_struct.oc_polarity = TMR_OUTPUT_ACTIVE_LOW;
	tmr_output_struct.oc_idle_state = TRUE;
	tmr_output_struct.occ_output_state = TRUE;
	tmr_output_struct.occ_polarity = TMR_OUTPUT_ACTIVE_HIGH;
	tmr_output_struct.occ_idle_state = FALSE;

	/* channel 1 */
//	tmr_output_channel_config(TMR3, TMR_SELECT_CHANNEL_1, &tmr_output_struct);
//	tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_1, channel1_pulse);

	/* channel 2 */
//	tmr_output_channel_config(TMR3, TMR_SELECT_CHANNEL_2, &tmr_output_struct);
//	tmr_channel_value_set(TMR3, TMR_SELECT_CHANNEL_2, channel2_pulse);

	/* channel 3 */
	tmr_output_channel_config(TMR5, TMR_SELECT_CHANNEL_3, &tmr_output_struct);
	tmr_channel_value_set(TMR5, TMR_SELECT_CHANNEL_3, channel3_pulse_5);

	/* channel 4 */
	tmr_output_channel_config(TMR5, TMR_SELECT_CHANNEL_4, &tmr_output_struct);
	tmr_channel_value_set(TMR5, TMR_SELECT_CHANNEL_4, channel4_pulse_5);

	tmr_channel_value_set(TMR5, TMR_SELECT_CHANNEL_4, 0); //Важно! Это выключает шим при запуске программы
	/* output enable */
	tmr_output_enable(TMR5, TRUE);

	/* enable tmr3 */
	tmr_counter_enable(TMR5, TRUE);
}

//void buzzer_handler(uint8_t count)
//{
//for (uint8_t i = 0; i < count; i++)
//  {
//	tmr_channel_value_set(TMR5, TMR_SELECT_CHANNEL_4, channel4_pulse_5); //включаем шим, выставленный в инициализации таймера
//	delay_ms(1000);
//	tmr_channel_value_set(TMR5, TMR_SELECT_CHANNEL_4, 0); //выключаем шим
//	delay_ms(1000);
//  }
//}

int main(void)
{
    i2c_status_type i2c_status;

    system_clock_config();
    at32_board_init();
	crm_clocks_freq_get(&crm_clocks_freq_struct);

    hi2cx.i2cx = I2Cx_PORT;
    i2c_config(&hi2cx);

    /* enable tmr/gpio clock */

    crm_configuration();
    wk_nvic_config();
    usart_configuration();
    i2c_interrupt_enable(I2C2, I2C_EVT_INT | I2C_DATA_INT | I2C_ERR_INT, TRUE);

    wk_gpio_init();
	wk_tmr1_init();
	wk_tmr3_init();
	wk_tmr6_init();
	wk_exint_config();
    mn_gpio_init();
	wk_tmr5_init();
	uint16_t speed = 750;
	holl_exint_init();
	PidParamInit();
	MotorAInit(&motorA);
	MotorBInit(&motorB);
	uint16_t channel_pulse;


    hi2cx.mode   = I2C_INT_SLA_RX;
	hi2cx.status = 1;
	hi2cx.pbuff  = rx_buf;
	hi2cx.pcount = 7;
	hi2cx.timeout = 0xffffffff;

    /* enable ack */
	i2c_ack_enable(I2C2, TRUE);
	i2c_interrupt_enable(I2C2, I2C_EVT_INT | I2C_DATA_INT | I2C_ERR_INT, TRUE);

	direction = CCW;
	gpio_bits_write(GPIOA, GPIO_PINS_6, TRUE);


	uint16_t new_led[BIT_NUMBER];
	size_t size = 360 * sizeof(uint16_t);
	turn_off_led(new_led);
	//set_color(new_led, 0, 45, 0);
	//set_single_led_color(new_led, 13, 0, 0, 255, 255);

	//set_led_number(new_led, 0, 0);
	memcpy(src_buffer, new_led, size);

	/* the Number of Pwm Output */
	PWM_DataLength = sizeof(src_buffer) / sizeof(src_buffer[0]);
	/* system clocks configuration */
	system_clock_config();

	/*board initialize interface init led and button	*/
	at32_board_init();

	work_param work;




	/* enable tmr/gpio clock */
	crm_configuration();

	/* tmr gpio configuration */
	gpio_configuration();

	/* dma configuration */
	dma_configuration();

	/* tmr configuration */
	tmr_configuration();

	/* enable tmr4 overflow dma request */
	tmr_dma_request_enable(TMR4, TMR_OVERFLOW_DMA_REQUEST, TRUE);

	work.red1 = 0;
	work.green1 = 0;
	work.blue1 =255;
	work.green2 = 0;
	work.red2 = 255;
	work.blue2 = 0;
	work.blue3 = 255;
	work.red3 = 255;
	work.green3 = 255;



	while (1) {

		motor_stop(motorA_ptr, motorB_ptr);
		motorB.setParrot = speed;
		usart2_tx_without_int();
		//набор скорости
		for (int i = 0; i < 750; i++) {
			//SetMotorPWM(&motorA, speed);
//			motorA.setParrot = speed;
			motorB.setParrot = speed;
			speed--;
			usart2_tx_without_int();
			led_wave(src_buffer, work.red1, work.green1, work.blue1);
			TMR4_DMA_Duty_Cycle();
	//		delay_us(1000);
			 //buzzer_handler(5);
			//servo_check();
			delay_ms(50);
		}
		//delay_sec(1);
		//сброс скорости
		for (int i = 0; i < 750; i++) {
			//SetMotorPWM(&motorA ,speed);
			//SetMotorPWM(&motorB, speed);
//			motorA.setParrot = speed;
			motorB.setParrot = speed;
			speed++;
			usart2_tx_without_int();
			//servo_check();
			led_wave(src_buffer, work.red1, work.green1, work.blue1);
			TMR4_DMA_Duty_Cycle();
			 //buzzer_handler(5);
//			delay_us(1000);
			delay_ms(50);
		}

		if (motorB.direction == CW) {
			motorB.direction = CCW;
		} else {
			motorB.direction = CW;
		}

//		buzzer_handler(5);
		uint16_t speed = 750;
		at32_led_on(LED2);

		//	set_single_led_color(src_buffer, 6, 255, 30, 255, 1);

	    //led_blink(src_buffer, &work);
		//led_wave(src_buffer, work.red1, work.green1, work.blue1);
		for (int i = 0; i < 1000000; i++)
			;

		TMR4_DMA_Duty_Cycle();
		delay_us(1000);

	}
}

/**
  * @}
  */

/**
  * @}
  */
